package emulator.shell.GUI.menu;

import com.jhe.hexed.JHexEditorData;

import emulator.cbm.Petscii;
import emulator.shell.GUI.debugger.CodeInfo;
import emulator.util.AddressRange;

public class MemoryQuery
{
	private JHexEditorData _data;
	private String _text;
	private int _position;
	private CodeInfo _codeInfo;

	public MemoryQuery(JHexEditorData data, String search_text, CodeInfo code_info) 
	{
		_data = data;
		_text = search_text;
		_codeInfo = code_info;
		_position = -1;
	}

	public boolean execute()
	{
		if (_text.length() == 0)
			return false;
		else if (_text.charAt(0) == '=' && _text.length() > 1)
		{
			if (_text.charAt(1) == '"')
			{
				int end = _text.indexOf('"', 2);
				if (end < 0)
					end = _text.length();
				byte [] values = new byte [end - 2];
				for (int i = 0; i < values.length; i++)
					values[i] = Petscii.asc2pet(_text.charAt(i+2));
				return find(values);
			}
			else
			{
				String[] value_parts = _text.substring(1).split("\\s+");
				try
				{
					if (value_parts.length > 0)
					{
						byte[] values = new byte [value_parts.length];
						for (int i = 0; i < value_parts.length; i++)
						{
							values[i] = (byte)(AddressRange.addressFromString(value_parts[i]) & 0xff);
						}
						return find(values);
					}
				}
				catch (NumberFormatException e)	{ }
			}
			return false;
		}
		else
		{
			return searchAddressOrLabel(_text);
		}
	}

	private boolean find(byte[] values)
	{
		_position = _data.find(values, _position+1);
		return _position >= 0;
	}

	private boolean searchAddressOrLabel(String search_text)
	{
		int address = -1;
		try { address = AddressRange.addressFromString(search_text); }
		catch (NumberFormatException e)	{ }
		try {
			if (address < 0 && _data.isAtOrigin())
			{	// label -> get address
				address = _codeInfo.findLabel(search_text);
			}
			_position = address;
			return true;
		}
		catch (Exception e)
		{

		}
		return false;
	}

	public int getPosition()
	{
		return _position;
	}

}
